package com.app.couponsharelife.ui.main.home.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.manage.Contacts.APP_LIFE_IMGURL
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.main.home.search.HQTGoodsListActivity
import com.app.couponsharelife.ui.main.home.shopweb.ShopWebActivity
import com.app.couponsharelife.ui.main.home.shopweb.TaoBaoWebActivity
import com.app.couponsharelife.ui.main.shop.JDShopActivity
import com.app.couponsharelife.ui.main.shop.PddShopActivity
import com.app.couponsharelife.ui.view.MarqueeView
import com.app.couponsharelife.ui.viewmodel.NewHomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import com.youth.banner.Banner
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.choiceness_rvitm.view.*
import kotlinx.android.synthetic.main.choiceness_shoprvitm.view.*
import kotlinx.android.synthetic.main.choiceness_womenrvitm.view.*
import kotlinx.android.synthetic.main.fragment_home_choiceness.*
import kotlinx.android.synthetic.main.home_choiceness_topitem.view.*
import java.lang.ref.WeakReference
import java.text.DecimalFormat
import java.util.HashMap

/**
 *Created by xct on 2019/2/12
 *Description:
 */
class HomeChoicenessFrag:LazyFragment() {
    private var broadcastList= arrayListOf<String>()
    private var bannerImgList= arrayListOf<TopBanner>()
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var womenGoodsList= arrayListOf<TaobaoGoodBean>()
    private var highGoodsList= arrayListOf<TaobaoGoodBean>()
    private var shopLayoutManager:LinearLayoutManager?=null
    private var womenAdapter:MyWomenAdapter?=null
    private var highAdapter:MyHighAdapter?=null
    private val shopList= arrayListOf<Label>()
    private var belowBanner:BelowBanner?=null
    private var mViewModel: NewHomeViewModel? = null
    private var myShopAdapter:MyShopAdapter?=null
    private var myAdapter:MyAdapter?=null
    private var pageIndex=1
    private var favoritesID="1"
    private var favorites99ID="1" //9.9包邮
    private var favorites99Name=""
    private var favorites20ID="1"  //20元封顶
    private var favorites20Name=""
    private var qqFavoritesID="1"  //全球好物
    private var qqFavoritesName=""
    private var tjFavoritesID="1"  //特价好物
    private var tjFavoritesName=""
    private var chFavoritesID="1"  //吃货福利
    private var chFavoritesName=""
    private var womenFavoritesID="1"  //女装好货
    private var highFavoritesID="1"  //高佣商品
    private var bannerFavoritesID=""  //中间banner
    private var bannerType=""  //中间bannertype
    private var bannerFavoritesName=""
    private var gradeID=""
    private var userPhone=""
    private var mHomeClassBean:HomeClassBean?=null
    private var bannerImageView:ImageView?=null
    private var marqueeView: MarqueeView?=null
    private var bannerView:Banner?=null
    private val TOPHOLDER1=1
    private val TOPHOLDER2=2
    private val TOPHOLDER3=3
    private val TOPHOLDER4=4
    private val ITMHOLDER=5
    private var handler:MyHandler?=null
    //private var viewPool:RecyclerView.RecycledViewPool?=null
    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    companion object {
        fun newInstance(homeClassBean:HomeClassBean): HomeChoicenessFrag {
            val fragment = HomeChoicenessFrag()
            val bundle= Bundle()
            bundle.putParcelable("Data",homeClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
    get() = R.layout.fragment_home_choiceness

    override fun initViews() {
        //viewPool=RecyclerView.RecycledViewPool()
        handler= MyHandler(this)
        setRefresh()
        val gridLayoutManager= GridLayoutManager(activity,2)
        gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return if (position == 0||position == 1||position == 2||position == 3) {
                    2
                } else {
                    1
                }
            }
        }
        choiceness_rv.layoutManager=gridLayoutManager
        myAdapter=MyAdapter()
        choiceness_rv.adapter=myAdapter
        //choiceness_rv.isNestedScrollingEnabled=false
        choiceness_rv.background.alpha=0
        choiceness_rv.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            private var totalDy=0
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                totalDy -= dy
                if (totalDy<1&&totalDy>-255){
                    choiceness_rv.background.alpha=0-totalDy
                }else{
                    choiceness_rv.background.alpha=255
                }
            }
            /*override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (RecyclerView.SCROLL_STATE_IDLE==newState){
                    (parentFragment as NewHomeFragment).visibilityAnim()
                }else{
                    (parentFragment as NewHomeFragment).goneAnim()
                }
            }*/
        })
        getHomeBase()
        getTopBanner()
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        choiceness_smartrefresh.setOnMultiPurposeListener(object : MyMultiPurposeListener{
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getFavorites(false,favoritesID)
            }

            override fun refresh() {
                pageIndex=1
                getFavorites(true,favoritesID)
                getBroadcast()
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun setShopRv(view:View){
        val layoutManager= GridLayoutManager(activity,5)//LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL,false)
        //view.choiceness_shoprv!!.setRecycledViewPool(viewPool)
        view.choiceness_shoprv.layoutManager=layoutManager
        view.choiceness_shoprv.setItemViewCacheSize(10)
        view.choiceness_shoprv.setHasFixedSize(true)
        myShopAdapter=MyShopAdapter()
        view.choiceness_shoprv.adapter=myShopAdapter
        /*view.choiceness_shoprv.setScrollSpeed(1)
        view.choiceness_shoprv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val layoutManager=recyclerView.layoutManager as LinearLayoutManager
                val firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
                if(firstCompletelyVisibleItemPosition==0) {
                    view.choiceness_shoprv.setType(true)
                }
                val lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition()
                if(lastCompletelyVisibleItemPosition==layoutManager.itemCount -1) {
                    view.choiceness_shoprv.setType(false)
                }
            }
        })*/
    }
    private fun setIntent(taobaoGoodBean:TaobaoGoodBean){
        val intent = Intent(context, GoodDetailActivity::class.java)
        intent.putExtra("good", taobaoGoodBean)
        startActivity(intent)
    }
    private fun startShopIntent(url:String,name:String,type:String){
        var intent:Intent?=null
        when(type){
            ""->{
                showToastMsg("正在开发中，敬请期待！")
                return
            }
            "PIN_DUO_DUO"->{ //拼多多
                intent= Intent(activity, PddShopActivity::class.java)
            }
            "CHONG_ZHI"->{  //充值中心

            }
            "JING_DONG"->{  //京东
                intent= Intent(activity, JDShopActivity::class.java)
            }
            "Link"->{  //网页
                intent= Intent(activity, ShopWebActivity::class.java)
                intent.putExtra("url",url)
                intent.putExtra("name", name)
            }
            "PRODUCT"->{  //选品库
                intent= Intent(activity, HQTGoodsListActivity::class.java)
                intent.putExtra("FavoritesID",url)
                intent.putExtra("Name",name)
            }
            "SDK_LINK"->{
                //goTaoBao(url)
                val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                if (relationId.isNotEmpty()) {
                    //val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                    intent = Intent(activity, TaoBaoWebActivity::class.java)
                    intent.putExtra("url", url+"&relationId=${relationId}")
                    intent.putExtra("name", name)
                }else{
                    getAliLonginUrl()
                }
            }
            "SDK_H5"->{
                val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                if (relationId.isNotEmpty()) {
                    //val relationId=AppUtils.getString(Contacts.ADZONE_ID, "")
                    intent = Intent(activity, TaoBaoWebActivity::class.java)
                    intent.putExtra("url", url+"&relationId=${relationId}")
                    intent.putExtra("name", name)
                }else{
                    getAliLonginUrl()
                }
            }
            else->{
                if (url.startsWith("http")){
                    intent= Intent(activity, ShopWebActivity::class.java)
                    intent.putExtra("url", url)
                    intent.putExtra("name", name)
                }else{
                    intent= Intent(activity, HQTGoodsListActivity::class.java)
                    intent.putExtra("FavoritesID",url)
                    intent.putExtra("Name",name)
                }
            }
        }
        /*when(name){
            ""->{
                showToastMsg("正在开发中，敬请期待！")
                return
            }
            "拼多多"->{
                intent= Intent(activity, PddShopActivity::class.java)
            }
            "京东"->{
                intent= Intent(activity, JDShopActivity::class.java)
            }
            "淘宝"->{
                intent= Intent(activity, HQTGoodsListActivity::class.java)
                intent.putExtra("FavoritesID",url)
                intent.putExtra("Name","海抢淘")
            }
            "充值中心"->{
                intent=Intent(activity, ChargeActivity::class.java)
            }
            else->{
                if (url.startsWith("http")){
                    intent= Intent(activity, ShopWebActivity::class.java)
                    intent.putExtra("url", url)
                    intent.putExtra("name", name)
                }else{
                    intent= Intent(activity, HQTGoodsListActivity::class.java)
                    intent.putExtra("FavoritesID",url)
                    intent.putExtra("Name",name)
                }
            }
        }*/
        if (intent!=null){
            startActivity(intent)
        }
    }
    private fun goTaoBao(url:String) {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改
        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID //+ AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = "65231850041"//AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["relationId"] = AppUtils.getString(Contacts.ADZONE_ID, "")
        /*val url = if (goodBean!!.coupon_share_url_new != "") goodBean!!.coupon_share_url_new else {
            if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        }*/
        if (url == "") {
            showToastMsg("该商品暂时不能购买")
            return
        }
        AlibcTrade.show(activity, AlibcPage(url+"?relationId=${AppUtils.getString(Contacts.ADZONE_ID, "")}"), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }
    private fun setFavoritesId(favorites:List<Favorite>){
        for (i in 0 until favorites.size){
            val favorite=favorites[i]
            if (favorite.name!!.contains("9.9")){
                favorites99ID=favorite.favoritesId.toString()
                favorites99Name=favorite.name?:""
            }
            if (favorite.name!!.contains("20")){
                favorites20ID=favorite.favoritesId.toString()
                favorites20Name=favorite.name?:""
            }
            if (favorite.name!!.contains("全球")){
                qqFavoritesID=favorite.favoritesId.toString()
                qqFavoritesName=favorite.name?:""
            }
            if (favorite.name!!.contains("特价")){
                tjFavoritesID=favorite.favoritesId.toString()
                tjFavoritesName=favorite.name?:""
            }
            if (favorite.name!!.contains("吃货")){
                chFavoritesID=favorite.favoritesId.toString()
                chFavoritesName=favorite.name?:""
            }
            if (favorite.name!!.contains("女装")){
                womenFavoritesID=favorite.favoritesId.toString()
                getWomenGoods(womenFavoritesID)
            }
            if (favorite.name!!.contains("高佣")){
                highFavoritesID=favorite.favoritesId.toString()
                getHighGoods(highFavoritesID)
            }
            if (favorite.name!!.contains("今日")){
                pageIndex=1
                favoritesID=favorite.favoritesId.toString()
                getFavorites(true,favoritesID)
            }
        }
    }
    private fun startBanner(){
        bannerView!!.isAutoPlay(true).startAutoPlay()
    }

    override fun lazyLoad() {

    }
    private fun getHomeBase(){
        showProgressDialog("请稍候")
        val map = HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        //map["theme"]="NEW_YEAR"
        //mViewModel?.freshHomeBase(map,isRefresh)
        RetrofitWorker.retrofitWorker.getHomeBase(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<HomeBaseBean>>(){
                    override fun onComplete() {

                    }
                    override fun onNext(it: RemoteResultBean<HomeBaseBean>) {
                        dismissProgressDialog()
                        if (it.data!=null) {
                            shopList.clear()
                            shopList.addAll(it.data!!.labels!!)
                            /*bannerImgList.clear()
                            bannerImgList.addAll(it.data!!.topBanner!!)
                            choiceness_mBanner.setImageLoader(GlideImageLoader())
                                    .setImages(bannerImgList)
                                    .setIndicatorGravity(BannerConfig.RIGHT)
                                    .setOnBannerListener {
                                        setBannerClic(bannerImgList[it])
                                    }
                                    .start()*/
                            //myAdapter!!.notifyDataSetChanged()
                            if (it.data!!.belowBanner!=null&&it.data!!.belowBanner!!.isNotEmpty()){
                                Glide.with(activity!!)
                                        .load(APP_LIFE_IMGURL+it.data!!.belowBanner!![0].imgPath)//APP_LIFE_IMGURL+it.data!!.belowBanner!![0].imgPath  "http://yiyepay.cn:8090/app/img/images/0.gif"
                                        .apply(RequestOptions().error(R.drawable.ic_app_place_holder2))
                                        .into(bannerImageView!!)
                                bannerFavoritesID=it.data!!.belowBanner!![0].link?:""
                                bannerType=it.data!!.belowBanner!![0].jumpType?:""
                                bannerFavoritesName=it.data!!.belowBanner!![0].name?:""
                            }
                            getBroadcast()
                            for (i in 0 until it.data!!.favorites!!.size){
                                val favorites=it.data!!.favorites!![i]
                                if (favorites.name!!.contains("9.9")){
                                    favorites99ID=favorites.favoritesId.toString()
                                }
                            }
                            if (it.data!!.favorites!=null&&it.data!!.favorites!!.isNotEmpty()){
                                setFavoritesId(it.data!!.favorites!!)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    private fun getAliLonginUrl(){
        showProgressDialog("加载中...")
        val map = HashMap<String, String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getAuthUrl(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            val url=it.data?:""
                            if (url.isNotEmpty()){
                                val intent= Intent(context, ShopWebActivity::class.java)
                                intent.putExtra("url", url)
                                intent.putExtra("name", "淘宝授权")
                                startActivity(intent)
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            if ("502"==e.code.toString()){

                            }
                        }else{
                            showToastMsg("数据加载出错！")
                        }
                    }
                })
    }
    private fun getBroadcast(){
        val map = HashMap<String, String>()
        //mViewModel?.freshBroadcast(map,isRefresh)
        RetrofitWorker.retrofitWorker.getBroadcast(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<List<HomeBroadcastBean>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<HomeBroadcastBean>>) {
                        if (it.data!=null){
                            broadcastList.clear()
                            val list=it.data!!
                            for (i in 0 until list.size){
                                broadcastList.add(list[i].itemName?:"")
                            }
                            marqueeView!!.startWithList(broadcastList)
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    private fun getTopBanner(){
        val map=HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        RetrofitWorker.retrofitWorker.getHomeTopBanner(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<List<TopBanner>>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<List<TopBanner>>) {
                        if (it.data!=null&&it.data!!.isNotEmpty()){
                            bannerImgList.clear()
                            bannerImgList.addAll(it.data!!)
                            bannerView!!.setImageLoader(GlideImageLoader())
                                    .setImages(bannerImgList)
                                    .setIndicatorGravity(BannerConfig.RIGHT)
                                    .setOnBannerListener {
                                        setBannerClic(bannerImgList[it])
                                    }
                                    .isAutoPlay(false)
                                    .start()
                            val message=Message()
                            message.what=0
                            handler!!.sendMessageDelayed(message,5000)
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private fun getWomenGoods(favoritesID:String){
        val map = HashMap<String, String>()
        map["pageNo"]="1"
        map["pageSize"]="6"
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["favoritesId"]=favoritesID
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewModel?.freshWomenFavorites(map,true)
        RetrofitWorker.retrofitWorker.getFavoritesItemPage(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<HomeChiocenGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeChiocenGoodsBean>) {
                        if (it.data!=null){
                            womenGoodsList.clear()
                            womenGoodsList.addAll(it.data!!.recordss as ArrayList<TaobaoGoodBean>)
                            womenAdapter!!.notifyDataSetChanged()
                        }
                    }

                    override fun onError(e: Throwable) {

                    }

                })
    }
    private fun getHighGoods(favoritesID:String){
        val map = HashMap<String, String>()
        map["pageNo"]="1"
        map["pageSize"]="6"
        map["userId"]=AppUtils.getString(Contacts.USERID,"1")
        map["favoritesId"]=favoritesID
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewModel?.freshHighFavorites(map,true)
        RetrofitWorker.retrofitWorker.getFavoritesItemPage(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<HomeChiocenGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeChiocenGoodsBean>) {
                        if (it.data!=null){
                            highGoodsList.clear()
                            highGoodsList.addAll(it.data!!.recordss)
                            highAdapter!!.notifyDataSetChanged()
                        }
                    }

                    override fun onError(e: Throwable) {

                    }
                })
    }
    private fun getFavorites(refresh: Boolean,favoritesID:String){
        val map = HashMap<String, String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["favoritesId"]=favoritesID
        //mViewModel?.freshFavorites(map,true)
        RetrofitWorker.retrofitWorker.getFavoritesItemPage(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().taobaoData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<HomeChiocenGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HomeChiocenGoodsBean>) {
                        if (it.data!=null){
                            choiceness_smartrefresh.finishLoadMore(2000)
                            if (refresh){
                                goodsList.clear()
                                if (it.data!!.recordss.size>0){
                                    choiceness_smartrefresh.finishRefresh()
                                    goodsList.addAll(it.data!!.recordss)
                                    myAdapter!!.notifyItemRangeChanged(1,goodsList.size)
                                    myAdapter!!.notifyDataSetChanged()
                                    pageIndex++
                                }else{
                                    choiceness_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                            }else{
                                if (it.data!!.recordss.size>0){
                                    choiceness_smartrefresh.finishLoadMore()
                                    goodsList.addAll(it.data!!.recordss)
                                    myAdapter!!.notifyItemRangeChanged(1,goodsList.size)
                                    pageIndex++
                                }else{
                                    choiceness_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (refresh){
                            choiceness_smartrefresh.finishRefresh()
                        }else{
                            choiceness_smartrefresh.finishLoadMore()
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            /*return if (0==viewType){
                val view=LayoutInflater.from(parent.context).inflate(R.layout.home_choiceness_topitem,parent,false)
                val viewHolder=MyTopHolder(view)
                viewHolder
            }else{
                val view=LayoutInflater.from(parent.context).inflate(R.layout.choiceness_rvitm,parent,false)
                MyHolder(view)
            }*/
            return when(viewType){
                TOPHOLDER1->{
                    val view=LayoutInflater.from(parent.context).inflate(R.layout.homefrag_rvtop,parent,false)
                    val viewHolder=MyTopHolder1(view)
                    viewHolder
                }
                TOPHOLDER2->{
                    val view=LayoutInflater.from(parent.context).inflate(R.layout.homefrag_rvtop1,parent,false)
                    val viewHolder=MyTopHolder2(view)
                    viewHolder
                }
                TOPHOLDER3->{
                    val view=LayoutInflater.from(parent.context).inflate(R.layout.homefrag_rvtop2,parent,false)
                    val viewHolder=MyTopHolder3(view)
                    viewHolder.setIsRecyclable(false)
                    viewHolder
                }
                TOPHOLDER4->{
                    val view=LayoutInflater.from(parent.context).inflate(R.layout.homefrag_rvtop3,parent,false)
                    val viewHolder=MyTopHolder4(view)
                    viewHolder.setIsRecyclable(false)
                    viewHolder
                }
                else->{
                    val view=LayoutInflater.from(parent.context).inflate(R.layout.choiceness_rvitm,parent,false)
                    MyHolder(view)
                }
            }
        }

        override fun getItemCount(): Int {
            return goodsList.size+4
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            /*if (holder is MyTopHolder){
                setShopRv(holder.itemView)
                holder.brokerageRv!!.layoutManager=GridLayoutManager(activity,3)
                holder.brokerageRv!!.setItemViewCacheSize(9)
                holder.brokerageRv!!.setHasFixedSize(true)
                //holder.brokerageRv!!.setRecycledViewPool(viewPool)
                highAdapter=MyHighAdapter()
                holder.brokerageRv!!.adapter=highAdapter
                holder.womenRv!!.layoutManager=GridLayoutManager(activity,3)
                //holder.womenRv!!.setRecycledViewPool(viewPool)
                holder.womenRv!!.scrollToPosition(9)
                holder.womenRv!!.setHasFixedSize(true)
                womenAdapter=MyWomenAdapter()
                holder.womenRv!!.adapter=womenAdapter
            }*/
            if (holder is MyTopHolder1){
                setShopRv(holder.itemView)
            }else if(holder is MyTopHolder2){

            }else if(holder is MyTopHolder3){
                holder.womenRv!!.layoutManager=GridLayoutManager(activity,3)
                //holder.womenRv!!.setRecycledViewPool(viewPool)
                holder.womenRv!!.scrollToPosition(9)
                holder.womenRv!!.setHasFixedSize(true)
                womenAdapter=MyWomenAdapter()
                holder.womenRv!!.adapter=womenAdapter
            }else if(holder is MyTopHolder4){
                holder.brokerageRv!!.layoutManager=GridLayoutManager(activity,3)
                holder.brokerageRv!!.setItemViewCacheSize(9)
                holder.brokerageRv!!.setHasFixedSize(true)
                //holder.brokerageRv!!.setRecycledViewPool(viewPool)
                highAdapter=MyHighAdapter()
                holder.brokerageRv!!.adapter=highAdapter
            }else if (holder is MyHolder){
                if (goodsList.size>0){
                    val df = DecimalFormat("#0.00")
                    val taobaoGoodBean=goodsList[position-4]
                    holder.goodsTitle!!.text=taobaoGoodBean.title
                    holder.goodsOldPrice!!.text=taobaoGoodBean.zk_final_price
                    if (taobaoGoodBean.has_coupon){
                        holder.goodsTextQh!!.text="券后"
                        holder.goodsCoupon!!.text=String.format("¥%s", df.format(taobaoGoodBean.coupon_price.toDouble()))
                        holder.couponLL!!.visibility=View.VISIBLE
                    }else{
                        holder.goodsTextQh!!.text="抢"
                        holder.couponLL!!.visibility=View.INVISIBLE
                    }
                    holder.oldpriceType!!.text=taobaoGoodBean.goodsSource+"价"
                    holder.goodsType!!.setImageResource(taobaoGoodBean.userType)
                    holder.goodsAward!!.text="￥${taobaoGoodBean.vip_commission}"
                    holder.goodsPrice!!.text="￥${taobaoGoodBean.final_price}"
                    holder.goodsSales!!.text=taobaoGoodBean.volume
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(taobaoGoodBean.pict_url)
                            .into(holder.goodsImag!!)
                    holder.itemView.setOnClickListener {
                        setIntent(taobaoGoodBean)
                    }
                }
            }
        }

        override fun getItemViewType(position: Int): Int {
            return when(position){
                0->{
                    TOPHOLDER1
                }
                1->{
                    TOPHOLDER2
                }
                2->{
                    TOPHOLDER3
                }
                3->{
                    TOPHOLDER4
                }
                else->{
                    ITMHOLDER
                }
            }
        }
    }
    inner class MyTopHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        var womenRv:RecyclerView?=null
        var brokerageRv:RecyclerView?=null
        var shopRv:RecyclerView?=null
        var activity:ImageView?=null
        var activity1:ImageView?=null
        var activity2:ImageView?=null
        var activity3:ImageView?=null
        var activity4:ImageView?=null
        var womenList:ConstraintLayout?=null
        var highList:ConstraintLayout?=null
       init {
           bannerImageView=itemView.choiceness_banner1
           marqueeView=itemView.choiceness_marqueeView
           womenRv=itemView.choiceness_womenrv
           brokerageRv=itemView.choiceness_brokeragerv
           shopRv=itemView.choiceness_shoprv
           bannerView=itemView.choiceness_mBanner
           activity=itemView.choiceness_activity1
           activity1=itemView.choiceness_activity2
           activity2=itemView.choiceness_activity3
           activity3=itemView.choiceness_activity4
           activity4=itemView.choiceness_activity5
           womenList=itemView.choiceness_llwomengoods
           highList=itemView.choiceness_llhighgoods
           bannerImageView!!.setOnClickListener { if (bannerFavoritesID.isNotEmpty()){ startShopIntent(bannerFavoritesID,bannerFavoritesName,"SDKLINK") } }
           activity!!.setOnClickListener{if (favorites99ID.isNotEmpty()){ startShopIntent(favorites99ID,favorites99Name,"PRODUCT") }}
           activity1!!.setOnClickListener{if (favorites20ID.isNotEmpty()){ startShopIntent(favorites20ID,favorites20Name,"PRODUCT")}}
           activity2!!.setOnClickListener{if (qqFavoritesID.isNotEmpty()){ startShopIntent(qqFavoritesID,qqFavoritesName,"PRODUCT")}}
           activity3!!.setOnClickListener{if (tjFavoritesID.isNotEmpty()){ startShopIntent(tjFavoritesID,tjFavoritesName,"PRODUCT")}}
           activity4!!.setOnClickListener{if (chFavoritesID.isNotEmpty()){ startShopIntent(chFavoritesID,chFavoritesName,"PRODUCT")}}
           womenList!!.setOnClickListener { if (womenFavoritesID.isNotEmpty()){ startShopIntent(womenFavoritesID,"女装尖货","PRODUCT")}}
           highList!!.setOnClickListener { if (highFavoritesID.isNotEmpty()){ startShopIntent(highFavoritesID,"高佣商品","PRODUCT")}}
       }
    }
    inner class MyTopHolder1(itemView:View):RecyclerView.ViewHolder(itemView){
        var shopRv:RecyclerView?=null
        init {
            bannerView=itemView.choiceness_mBanner
            shopRv=itemView.choiceness_shoprv
        }
    }
    inner class MyTopHolder2(itemView:View):RecyclerView.ViewHolder(itemView){
        var activity:ImageView?=null
        var activity1:ImageView?=null
        var activity2:ImageView?=null
        var activity3:ImageView?=null
        var activity4:ImageView?=null
        init {
            bannerImageView=itemView.choiceness_banner1
            marqueeView=itemView.choiceness_marqueeView
            activity=itemView.choiceness_activity1
            activity1=itemView.choiceness_activity2
            activity2=itemView.choiceness_activity3
            activity3=itemView.choiceness_activity4
            activity4=itemView.choiceness_activity5
            bannerImageView!!.setOnClickListener { if (bannerFavoritesID.isNotEmpty()){ startShopIntent(bannerFavoritesID,bannerFavoritesName,bannerType) } }
            activity!!.setOnClickListener{if (favorites99ID.isNotEmpty()){ startShopIntent(favorites99ID,favorites99Name,"PRODUCT") }}
            activity1!!.setOnClickListener{if (favorites20ID.isNotEmpty()){ startShopIntent(favorites20ID,favorites20Name,"PRODUCT")}}
            activity2!!.setOnClickListener{if (qqFavoritesID.isNotEmpty()){ startShopIntent(qqFavoritesID,qqFavoritesName,"PRODUCT")}}
            activity3!!.setOnClickListener{if (tjFavoritesID.isNotEmpty()){ startShopIntent(tjFavoritesID,tjFavoritesName,"PRODUCT")}}
            activity4!!.setOnClickListener{if (chFavoritesID.isNotEmpty()){ startShopIntent(chFavoritesID,chFavoritesName,"PRODUCT")}}
        }
    }
    inner class MyTopHolder3(itemView:View):RecyclerView.ViewHolder(itemView){
        var womenList:ConstraintLayout?=null
        var womenRv:RecyclerView?=null
        init {
            womenList=itemView.choiceness_llwomengoods
            womenRv=itemView.choiceness_womenrv
            womenList!!.setOnClickListener { if (womenFavoritesID.isNotEmpty()){ startShopIntent(womenFavoritesID,"女装尖货","PRODUCT")}}
        }
    }
    inner class MyTopHolder4(itemView:View):RecyclerView.ViewHolder(itemView){
        var highList:ConstraintLayout?=null
        var brokerageRv:RecyclerView?=null
        init {
            highList=itemView.choiceness_llhighgoods
            brokerageRv=itemView.choiceness_brokeragerv
            highList!!.setOnClickListener { if (highFavoritesID.isNotEmpty()){ startShopIntent(highFavoritesID,"高佣商品","PRODUCT")}}
        }
    }
    inner class MyHolder(itemview: View):RecyclerView.ViewHolder(itemview){
        var goodsTitle:TextView?=null
        var goodsImag:ImageView?=null
        var goodsOldPrice:TextView?=null
        var goodsPrice:TextView?=null
        var goodsCoupon:TextView?=null
        var goodsAward:TextView?=null
        var goodsSales:TextView?=null
        var goodsType:ImageView?=null
        var couponLL:LinearLayout?=null
        var goodsTextQh:TextView?=null
        var oldpriceType:TextView?=null
        init {
            goodsTitle=itemView.choiceness_rvitm_title
            goodsImag=itemview.choiceness_rvitm_img
            goodsOldPrice=itemview.choiceness_rvitm_oldprice
            goodsPrice=itemview.choiceness_rvitm_price
            goodsCoupon=itemview.choiceness_rvitm_quanprice
            goodsAward=itemview.choiceness_rvitm_jiangprice
            goodsSales=itemview.choiceness_rvitm_yuenumber
            goodsType=itemview.choiceness_rvitm_imgtype
            couponLL=itemview.choiceness_rvitm_llq1
            goodsTextQh=itemView.choiceness_rvitm_qh
            oldpriceType=itemView.choiceness_rvitm_oldpricetype
            goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
        }
    }
    inner class MyShopAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.choiceness_shoprvitm,parent,false)
            return MyShopHolder(view)
        }

        override fun getItemCount(): Int {
            return shopList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is MyShopHolder){
                if (shopList.size>0){
                    holder.textView!!.text=shopList[position].name
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(Contacts.REMOTE_IMAGE_URL +shopList[position].imgPath)
                            .into(holder.imageView!!)
                    holder.itemView.setOnClickListener {
                        val url=if (shopList[position].link.isEmpty()){
                            shopList[position].id.toString()
                        }else{
                            shopList[position].link
                        }
                        startShopIntent(url?:"",shopList[position].name?:"",shopList[position].type?:"")
                    }
                }
            }
        }
    }
    inner class MyShopHolder(itemview: View):RecyclerView.ViewHolder(itemview){
        var textView: TextView?=null
        var imageView: ImageView?=null
        init {
            textView=itemview.choiceness_shoprvitm_name
            imageView=itemview.choiceness_shoprvitm_img
        }
    }
    inner class MyWomenAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.choiceness_womenrvitm,parent,false)
            return MyWomenHolder(view)
        }

        override fun getItemCount(): Int {
            return womenGoodsList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is MyWomenHolder){
                if (womenGoodsList.size>0){
                    val taobaoGoodBean=womenGoodsList[position]
                    val df = DecimalFormat("#0.00")
                    holder.goodsTitle!!.text=taobaoGoodBean.title
                    holder.goodsOldPrice!!.text=taobaoGoodBean.zk_final_price
                    //holder.goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG and Paint.ANTI_ALIAS_FLAG
                    if (taobaoGoodBean.has_coupon){
                        holder.goodsTextQh!!.text="券后"
                        holder.goodsCoupon!!.text=String.format("¥%s", df.format(taobaoGoodBean.coupon_price.toDouble()))
                        holder.couponLL!!.visibility=View.VISIBLE
                    }else{
                        holder.goodsTextQh!!.text="抢"
                        holder.couponLL!!.visibility=View.INVISIBLE
                    }
                    holder.goodsPrice!!.text=taobaoGoodBean.final_price
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(taobaoGoodBean.pict_url)
                            .into(holder.goodsImag!!)
                    holder.itemView.setOnClickListener {
                        setIntent(taobaoGoodBean)
                    }
                }
            }
        }
    }
    inner class MyWomenHolder(itemview: View):RecyclerView.ViewHolder(itemview){
        var goodsTitle: TextView?=null
        var goodsImag: ImageView?=null
        var goodsOldPrice: TextView?=null
        var goodsPrice: TextView?=null
        var goodsCoupon: TextView?=null
        var couponLL: LinearLayout?=null
        var goodsTextQh: TextView?=null
        init {
            goodsTitle=itemview.choiceness_womenrvitm_title
            goodsImag=itemview.choiceness_womenrvitm_img
            goodsOldPrice=itemview.choiceness_womenrvitm_oldprice
            goodsPrice=itemview.choiceness_womenrvitm_price
            goodsCoupon=itemview.choiceness_womenrvitm_couponprice
            couponLL=itemview.choiceness_womenrvitm_llcoupon
            goodsTextQh=itemview.choiceness_womenrvitm_qh
            goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
        }
    }
    inner class MyHighAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view=LayoutInflater.from(parent.context).inflate(R.layout.choiceness_womenrvitm,parent,false)
            return MyHighHolder(view)
        }

        override fun getItemCount(): Int {
            return highGoodsList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (holder is MyHighHolder){
                if (highGoodsList.size>0){
                    val taobaoGoodBean=highGoodsList[position]
                    val df = DecimalFormat("#0.00")
                    holder.goodsTitle!!.text=taobaoGoodBean.title
                    holder.goodsOldPrice!!.text=taobaoGoodBean.zk_final_price
                    //holder.goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG and Paint.ANTI_ALIAS_FLAG
                    if (taobaoGoodBean.has_coupon){
                        holder.goodsTextQh!!.text="券后"
                        holder.goodsCoupon!!.text=String.format("¥%s", df.format(taobaoGoodBean.coupon_price.toDouble()))
                        holder.couponLL!!.visibility=View.VISIBLE
                    }else{
                        holder.goodsTextQh!!.text="抢"
                        holder.couponLL!!.visibility=View.INVISIBLE
                    }
                    holder.goodsPrice!!.text=taobaoGoodBean.final_price
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(taobaoGoodBean.pict_url)
                            .into(holder.goodsImag!!)
                    holder.itemView.setOnClickListener {
                        setIntent(taobaoGoodBean)
                    }
                }
            }
        }
    }
    inner class MyHighHolder(itemview: View):RecyclerView.ViewHolder(itemview){
        var goodsTitle: TextView?=null
        var goodsImag: ImageView?=null
        var goodsOldPrice: TextView?=null
        var goodsPrice: TextView?=null
        var goodsCoupon: TextView?=null
        var couponLL: LinearLayout?=null
        var goodsTextQh: TextView?=null
        init {
            goodsTitle=itemview.choiceness_womenrvitm_title
            goodsImag=itemview.choiceness_womenrvitm_img
            goodsOldPrice=itemview.choiceness_womenrvitm_oldprice
            goodsPrice=itemview.choiceness_womenrvitm_price
            goodsCoupon=itemview.choiceness_womenrvitm_couponprice
            couponLL=itemview.choiceness_womenrvitm_llcoupon
            goodsTextQh=itemview.choiceness_womenrvitm_qh
            goodsOldPrice!!.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
        }
    }
    inner class GlideImageLoader: ImageLoader(){
        override fun displayImage(context: Context, path: Any, imageView: ImageView) {
            val pading=AppUtils.dip2px(context,12f)
            imageView.setPadding(pading,0,pading,0)
            val topBanner=path as TopBanner
            Glide.with(context).asBitmap()
                    .apply(RequestOptions().transforms(CenterCrop(), RoundedCorners( 15)).error(R.drawable.ic_app_place_holder2))
                    .load(Contacts.APP_LIFE_IMGURL +topBanner.imgPath)
                    .into(imageView)
        }
    }
    private class MyHandler(fragment: HomeChoicenessFrag) : Handler() {
        private val mActivity: WeakReference<HomeChoicenessFrag> = WeakReference<HomeChoicenessFrag>(fragment)
        private var activity:HomeChoicenessFrag?=null
        override fun handleMessage(msg: Message) {
            if (activity== null) {
                activity=mActivity.get()
            }
            when (msg.what) {
                0 -> {
                    activity!!.startBanner()
                }
                else -> {

                }
            }
        }
    }
}